<template>
  <div>
    <el-switch v-model="draggable" active-text="拖拽开" inactive-text="拖拽关">
    </el-switch>
    <el-button type="primary" round v-if="draggable" @click="submitDrag"
    >保存批量拖拽
    </el-button
    >
    <el-button type="danger" icon="el-icon-delete" circle @click="batchDelete"
    >批量删除
    </el-button
    >
    <el-tree
      :data="menu"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
      node-key="catId"
      :default-expanded-keys="expandedKey"
      show-checkbox
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleNodeDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="data.catLevel < 3"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="data.children == null"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>

          <el-button type="text" size="mini" @click="() => modify(data)">
            Update
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="单位" :label-width="formLabelWidth">
          <el-input v-model="form.productUnit" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" :label-width="formLabelWidth">
          <el-input v-model="form.icon" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="() => submitEdit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data () {
    return {
      draggable: false,
      updateLevel: [],
      maxcatLevel: 0,
      dialogFormVisible: false,
      form: {
        catId: '',
        name: '',
        icon: '',
        productUnit: '',
      },
      formLabelWidth: '120px',
      expandedKey: [],
      menu: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
    }
  },
  methods: {
    handleNodeClick (data) {
      console.log(data)
    },

    getMenus () {
      this.$http({
        url: this.$http.adornUrl('/gulimailproduct/category/list/tree'),
        method: 'get',
      }).then(({data}) => {
        console.log('成功获取到数据。。', data.data)
        this.menu = data.data
      })
    },

    append (data) {
      console.log('点击append', data)
      this.$prompt('请输入分类名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:
        //   /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        // inputErrorMessage: "邮箱格式不正确",
      })
        .then(({value}) => {
          var categoryEntity = {
            catLevel: data.catLevel + 1,
            parentCid: data.catId,
            name: value,
            showStatus: 1,
            sort: 0,
            productCount: 0,
          }
          console.log('新增', categoryEntity)
          this.$http({
            url: this.$http.adornUrl('/gulimailproduct/category/save'),
            method: 'post',
            data: this.$http.adornData(categoryEntity, false),
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '新增成功',
                type: 'success',
                duration: 1500,
              })
              this.getMenus()
              this.expandedKey = [categoryEntity.parentCid]
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入',
          })
        })
    },

    remove (node, data) {
      console.log('点击remove', node, data)
      var ids = [data.catId]
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/gulimailproduct/category/deleteByIds'),
            method: 'post',
            data: this.$http.adornData(ids, false),
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500,
              })
              this.getMenus()
              this.expandedKey = [node.parent.data.catId]
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },

    modify (data) {
      this.dialogFormVisible = true
      this.form.catId = data.catId
      console.log(this.form.catId)
      this.$http({
        url: this.$http.adornUrl(
          `/gulimailproduct/category/info/${data.catId}`
        ),
        method: 'get',
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.form.name = data.category.name
          this.form.icon = data.category.icon
          this.form.productUnit = data.category.productUnit
        }
      })
    },
    submitEdit () {
      this.dialogFormVisible = false
      var CategoryEntity = {
        catId: this.form.catId,
        name: this.form.name,
        icon: this.form.icon,
        productUnit: this.form.productUnit,
      }
      console.log(CategoryEntity)
      this.$http({
        url: this.$http.adornUrl('/gulimailproduct/category/update'),
        method: 'post',
        data: this.$http.adornData(CategoryEntity, false),
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '修改成功',
            type: 'success',
            duration: 1500,
          })
          this.getMenus()
          // this.expandedKey = [node.parent.data.catId];
        }
      })
    },
    allowDrop (draggingNode, dropNode, type) {
      console.log(draggingNode, dropNode, type)
      this.maxcatLevel = draggingNode.data.catLevel
      this.getDraggingNodeLevel(draggingNode.data)
      console.log(this.maxcatLevel - draggingNode.data.catLevel + 1)
      if (type === 'inner') {
        return (
          this.maxcatLevel -
          draggingNode.data.catLevel +
          1 +
          dropNode.data.catLevel <=
          3
        )
      } else {
        return (
          this.maxcatLevel -
          draggingNode.data.catLevel +
          1 +
          dropNode.parent.level <=
          3
        )
      }
    },
    getDraggingNodeLevel (node) {
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxcatLevel) {
            this.maxcatLevel = node.children[i].catLevel
          }
          this.getDraggingNodeLevel(node.children[i])
        }
      }
    },
    handleNodeDrop (draggingNode, dropNode, type, event) {
      console.log('拖拽完成', draggingNode, dropNode, type, event)

      // 更新 dropNode 父节点下的排序
      dropNode.parent.childNodes.forEach((child, index) => {
        const updateData = {
          catId: child.data.catId,
          sort: index,
        }

        if (child.data.catId === draggingNode.data.catId) {
          // 当找到匹配节点时，处理不同的 level
          if (child.level === child.data.catLevel) {
            this.updateLevel.push(updateData) // 仅更新排序
          } else {
            if (child.level == 1) {
              this.updateLevel.push({
                ...updateData,
                catLevel: child.level,
                parentCid: 0,
              })
            } else {
              this.updateLevel.push({
                ...updateData,
                catLevel: child.level,
                parentCid: dropNode.data.parentCid,
              })
            }
            this.updateChild(child.childNodes) // 递归处理子节点
          }
        } else {
          this.updateLevel.push(updateData)
        }
      })
      this.expandedKey.push(draggingNode.data.parentCid)

      console.log(this.updateLevel)
    },

    updateChild (children) {
      if (children && children.length > 0) {
        children.forEach((child) => {
          this.updateLevel.push({
            catId: child.data.catId,
            catLevel: child.level,
          })
          this.updateChild(child.childNodes) // 递归处理子节点
        })
      }
    },
    submitDrag () {
      if (this.updateLevel.length == 0) {
        this.$message({
          message: '无修改，不需要提交',
          type: 'error',
          duration: 1500,
        })
        return
      }
      this.$http({
        url: this.$http.adornUrl('/gulimailproduct/category/updateByDragging'),
        method: 'post',
        data: this.$http.adornData(this.updateLevel, false),
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '拖拽成功',
            type: 'success',
            duration: 1500,
          })
          this.getMenus()
        } else {
          this.$message({
            message: data.message || '拖拽失败',
            type: 'error',
            duration: 1500,
          })
        }
      })
      this.updateLevel.length = 0
      this.expandedKey.length = 0 // 清空 updateLevel
    },
    batchDelete () {
      let cheakNodes = this.$refs.menuTree.getCheckedNodes()
      console.log(cheakNodes)
      if (cheakNodes == null || cheakNodes.length == 0) {
        this.$message({
          message: '没有选中',
          type: 'error',
          duration: 1500,
        })
        return
      }
      let catIds = []
      for (let i = 0; i < cheakNodes.length; i++) {
        catIds.push(cheakNodes[i].catId)
      }
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/gulimailproduct/category/deleteByIds'),
            method: 'post',
            data: this.$http.adornData(catIds, false),
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500,
              })
              this.getMenus()
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
  created () {
    this.getMenus();
  },
};
</script>
